package day52.org.service.impl;

import day52.basic.commonenum.ErrorCode;
import day52.basic.constants.Constant;
import day52.basic.exception.CustomException;
import day52.basic.util.BaiduAuditUtils;
import day52.basic.util.PageList;
import day52.org.domain.Employee;
import day52.org.domain.Shop;
import day52.org.domain.ShopAuditLog;
import day52.org.mapper.EmployeeMapper;
import day52.org.mapper.ShopAuditLogMapper;
import day52.org.mapper.ShopMapper;
import day52.org.query.ShopQuery;
import day52.org.service.IShopService;
import day52.basic.service.impl.BaseServiceImpl;
import day52.user.domain.Logininfo;
import day52.user.mapper.LogininfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yang
 * @since 2022-12-17
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public void settle(Shop shop) {
        //参数校验
        //两次密码是否一致
        if(!shop.getAdmin().getPassword().equals(shop.getAdmin().getComfirmPassword())){
            throw new CustomException(ErrorCode.PASSWORDS_INCONSISTENT.getCode());
        }
        //校验店铺是否注册过
        Shop shopTmp = shopMapper.findByName(shop.getName());
        if(shopTmp != null){
            throw new CustomException(ErrorCode.SHOP_EXISTS.getCode());
        }
        Boolean auditFlag = false;
        //百度Ai审核
        auditFlag = BaiduAuditUtils.TextCensor(shop.getName());
        if(!auditFlag){
            throw new CustomException(ErrorCode.CONTENT_AUDIT_FAILED.getCode());
        }
        //图片审核
        if(shop.getLogo() != null){
            auditFlag = BaiduAuditUtils.ImgCensor(Constant.IMG_SHOW_URL + shop.getLogo());
        }
        if(!auditFlag){
            throw new CustomException(ErrorCode.CONTENT_AUDIT_FAILED.getCode());
        }

        //初始化店铺状态
        shop.setState(0);
        //店铺初始化注册时间
        shop.setRegisterTime(new Date());
        //保存店铺
        shopMapper.add(shop);
        //店长是否注册过
        Employee emp = employeeMapper.findByUserName(shop.getAdmin().getUsername());
        //店长如果注册过是否是别的店铺的
        if(emp != null && emp.getShop_id() != null){
            throw new CustomException(ErrorCode.EMP_SHOP_EXISTS.getCode());
        }
        //如果店长存在但是没有shop_id就直接绑定本次shop的id
        if(emp != null){
            //员工有，并且可以成为这次的店长，绑定店铺id
            emp.setShop(shop);
            shop.setAdminId(emp.getId());
        }else{
            //员工绑定店铺id
            emp = shop.getAdmin();
            emp.setShop(shop);
            //给新增的员工添加状态
            emp.setState(0);
            //添加员工
            employeeMapper.add(emp);
            //给店铺绑定店长
            shop.setAdminId(emp.getId());
        }
        //更新店铺
        shopMapper.update(shop);
    }

    @Override
    @Transactional
    public void pass(ShopAuditLog shopAuditLog) {
        //修改店铺状态
        Shop shop = shopMapper.findOne(shopAuditLog.getShopId());
        shop.setState(2);//修改为店铺状态待激活状态
        shopMapper.update(shop);

        //设置审核日志状态，1通过，0驳回
        shopAuditLog.setState(1);
        //设置审核人(以后做成动态的)
        shopAuditLog.setAuditId(334L);
        //设置审核时间
        shopAuditLog.setAuditTime(new Date());
        //保存到数据库
        shopAuditLogMapper.add(shopAuditLog);

//        //发送激活邮件
//        SimpleMailMessage sm = new SimpleMailMessage();
//        //发件人
//        sm.setFrom("937055710@qq.com");
//        //收件人
//        Employee emp = employeeMapper.findOne(shop.getAdminId());
//        String email = emp.getEmail();
//        sm.setTo(email);
//        //标题
//        sm.setSubject("宠物之家激活邮件！");
//        //内容
//        sm.setText("http://localhost:8080/shop/active/"+shop.getId());
//        javaMailSender.send(sm);
    }

    @Override
    @Transactional
    public void reject(ShopAuditLog shopAuditLog) {
        //修改店铺状态
        Shop shop = shopMapper.findOne(shopAuditLog.getShopId());
        shop.setState(-1);//修改为店铺状态驳回状态
        shopMapper.update(shop);

        //设置审核日志状态，1通过，0驳回
        shopAuditLog.setState(0);
        //设置审核人(以后做成动态的)
        shopAuditLog.setAuditId(334L);
        //设置审核时间
        shopAuditLog.setAuditTime(new Date());
        //保存到数据库
        shopAuditLogMapper.add(shopAuditLog);

//        //店铺关联的管理员
//        Employee manager = employeeMapper.findOne(shop.getAdminId());
//        //3.发送邮件通知 商家 审核失败，告知原因，修改的地址
//        //创建复杂邮件对象
//        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//        //使用工具类来构建消息
//        MimeMessageHelper helper = null;
//        try {
//            helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//            //设置发件人
//            helper.setFrom("937055710@qq.com");
//            //设置邮件主题
//            helper.setSubject("审核失败通知");
//            //邮件正文
//            helper.setText("<h1>审核失败</h1><br>"+
//                    "<span>失败原因："+shopAuditLog.getNote()+"</span><br>"+
//                    "<a href='http://127.0.0.1:8081/#/register2?id="+shop.getId()+"'>点击修改资料</a>",true);
//            helper.setTo(manager.getEmail());
//            //发送消息
//            javaMailSender.send(mimeMessage);
//        } catch (MessagingException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void batchAdd(List<Shop> shops) {
        shopMapper.batchAdd(shops);
    }

    @Override
    public PageList<Shop> pageQuery(ShopQuery query) {
        List<Shop> shops = shopMapper.pageQuery(query);
        shops.forEach(shop -> {
            //查询审核记录
            List<ShopAuditLog> shopAuditLogs = shopAuditLogMapper.findByShopId(shop.getId());
            shopAuditLogs.forEach(shopAuditLog -> {
                //查询审核员
                Employee auditManager = employeeMapper.findOne(shopAuditLog.getAuditId());
                //添加审核员
                shopAuditLog.setAuditManager(auditManager);
            });
            //添加审核记录
            shop.setShopAuditLog(shopAuditLogs);
        });
        return new PageList<Shop>(shopMapper.count(query),shops);
    }
}
